package org.xlx.xlx_oa.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import org.xlx.xlx_oa.common.Constant;
import org.xlx.xlx_oa.utils.ThreadLocalUtil;

import java.time.LocalDateTime;

@Slf4j
@Component
public class GlobalMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        LocalDateTime dateTime = LocalDateTime.now();
        this.setFieldValByName("createdDateTime", dateTime, metaObject);
        this.setFieldValByName("updatedDateTime", dateTime, metaObject);
        if (ThreadLocalUtil.get(Constant.USERID) != null) {
            Long userId = Long.valueOf(ThreadLocalUtil.get(Constant.USERID).toString());
            this.setFieldValByName("createdId", userId, metaObject);
            this.setFieldValByName("updatedId", userId, metaObject);
        } else {
            this.setFieldValByName("createdId", -1L, metaObject);
            this.setFieldValByName("updatedId", -1L, metaObject);
        }
        if (ThreadLocalUtil.get(Constant.USERNAME) != null) {
            String userName = ThreadLocalUtil.get(Constant.USERNAME).toString();
            this.setFieldValByName("creatorName", userName, metaObject);
            this.setFieldValByName("modifierName", userName, metaObject);
        } else {
            this.setFieldValByName("creatorName", "", metaObject);
            this.setFieldValByName("modifierName", "", metaObject);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.setFieldValByName("updatedDateTime", LocalDateTime.now(), metaObject);
        if (ThreadLocalUtil.get(Constant.USERID) != null) {
            Long userId = Long.valueOf(ThreadLocalUtil.get(Constant.USERID).toString());
            this.setFieldValByName("updatedId", userId, metaObject);
        } else {
            this.setFieldValByName("updatedId", -1L, metaObject);
        }
        if (ThreadLocalUtil.get(Constant.USERNAME) != null) {
            String userName = ThreadLocalUtil.get(Constant.USERNAME).toString();
            this.setFieldValByName("modifierName", userName, metaObject);
        } else {
            this.setFieldValByName("modifierName", "", metaObject);
        }
    }
}